<!--
 * @Author: zxh
 * @Email: 1271027008@qq.com
 * @Date: 2020-05-25 15:19:05
 * @Descripttion: 
--> 
<template>
    <div class="real-time-data">
        <el-row :gutter="20">
            <el-col v-if="userType == 3 || userType == 4 || userType == 6" :span="3" class="left-tree">
                <el-row>
                    <h4 class="title">所有客户</h4>
                </el-row>
                <el-row class="el-row-sumlink">
                    <a href="javascript:void(0);" class="check" @click="lookSummary">查看汇总</a>
                </el-row>
                <ul class="company">
                    <li
                        class="company-item"
                        v-for="(item,index) in companyList"
                        :key="index"
                        @click="chooseCompany(item.deptId)"
                        :class="{'active':isActive==item.deptId}"
                    >{{item.companyName}}</li>
                </ul>
                <!-- <el-tree highlight-current :data="data" @node-click="handleNodeClick" class='el-tree-border'></el-tree> -->
            </el-col>
            <el-col :span="this.userType == 3 || this.userType == 4 || this.userType == 6 ? 21 : 24">
                <el-row>
                    <span style="padding-left:20px;font-size:12px;color:#999">企业名称</span>
                    <h2 class="sub-title">{{title}}</h2>
                </el-row>
                <el-row class="line-2">
                    <span>终端数量：</span> {{doorCount}}
                </el-row>
                <el-row style="padding-left:20px">
                    <el-date-picker v-model="dateValue" type="date" placeholder="选择日期" value-format='yyyy-MM-dd' :clearable="false" @change="search"></el-date-picker>
                    <!-- <el-button type="primary" class="theme_bg" @click="search">搜索</el-button>
                    <el-button type="default" class="theme_color" @click="reset">清除</el-button> -->
                </el-row>
                <el-row class="line-4">
                    <el-tabs v-model="activeName">
                        <el-tab-pane label="曲线分析" name="first">
                            <el-row>
                                <el-col :span="6">
                                    <table cellspacing="0" cellpadding="0" border="0" class="el-table" style="width: 98%">
                                        <tr>
                                            <th colspan="1" rowspan="1" class="is-leaf"><div class="cell">时间</div></th>
                                            <th colspan="1" rowspan="1" class="is-leaf">
                                                <div v-if="isLookSummary" class="cell">
                                                    <el-tooltip class="item" effect="light" :content="prompting" placement="bottom-start">
                                                        <i class="el-icon-warning-outline"></i>
                                                    </el-tooltip>
                                                    历史趋势
                                                </div>
                                                <div v-if="isLookSummary == false" class="cell">
                                                    历史趋势
                                                </div>
                                            </th>
                                            <th colspan="1" rowspan="1" class="is-leaf"><div class="cell">日前填报</div></th>
                                            <th colspan="1" rowspan="1" class="is-leaf" v-if="isLookSummary"><div class="cell">修正量</div></th>
                                        </tr>
                                    </table>
                                    <el-table :data="tableDataLine" height="470" style="width: 98%" :show-header="false">
                                        <el-table-column prop="time" label="时间"></el-table-column>
                                        <el-table-column prop="avgNumber" label="前三日实时数据参考"></el-table-column>
                                        <el-table-column prop="forecastNumber" label="日前填报"></el-table-column>
                                        <el-table-column v-if="isLookSummary" label="修正量">
                                            <template slot-scope="scope">
                                                <el-input v-model="scope.row.correctNumber" class="input-value" @focus="bindCorrectNumber(scope.row.correctNumber)" @blur="editCorrectNumber(scope.row, scope.row.correctNumber)"></el-input>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                    <div v-if="isLookSummary" class="total_line_1">
                                        <span>
                                            <b>合计</b>
                                        </span>
                                        <span>
                                            <b>{{sumAvgNumber}}</b>
                                        </span>
                                        <span>
                                            <b>{{sumForecastNumber}}</b>
                                        </span>
                                        <span>
                                            <b>{{sumCorrectNumber}}</b>
                                        </span>
                                    </div>
                                    <div v-else class="total_line_1">
                                        <span class="span30">
                                            <b>合计</b>
                                        </span>
                                        <span class="span30">
                                            <b>{{sumAvgNumber}}</b>
                                        </span>
                                        <span class="span30">
                                            <b>{{sumForecastNumber}}</b>
                                        </span>
                                    </div>
                                    <el-button v-if="isLookSummary" type="primary" style="width:98%" class="theme_bg" @click="exportExcel">一键导出</el-button>
                                </el-col>
                                <el-col :span="18">
                                    <!-- <el-row style="text-align:right">
                                        <el-select v-model="elecValue" placeholder="请选择综合电量">
                                            <el-option v-for="item in options" :key="item.value" 
                                                :label="item.label" :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </el-row> -->
                                    <div id="chart_box" style="width: 100%;height: 550px;"></div>
                                </el-col>
                            </el-row>
                        </el-tab-pane>
                        <el-tab-pane label="采集数据" name="second">
                            <el-row>
                                <el-table :data="tableData1" style="width: 100%;" class="overflowX" height="457">
                                    <el-table-column fixed label="企业名称" width="150">
                                        <template slot-scope="scope">
                                            <a :href="scope.row.href" class="theme_color">{{scope.row.name}}</a>
                                        </template>
                                    </el-table-column>
                                    <el-table-column fixed prop="date" label="日期" width="100"></el-table-column>
                                    <el-table-column :prop="item" v-for="(item, index) in data" :key="index" :label="item"></el-table-column>
                                    <el-table-column fixed="right" label="操作">
                                        <template slot-scope="scope">
                                            <el-button @click="showDetail(scope.row)" type="text" size="small">查看</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                                <!-- 分页 -->
                                <el-pagination
                                    style="margin-top: 8px;"
                                    @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange"
                                    :current-page="index"
                                    :page-size="size"
                                    layout="total, sizes, prev, pager, next, jumper"
                                    :total="tableTotal"
                                ></el-pagination>
                            </el-row>
                        </el-tab-pane>
                    </el-tabs>
                </el-row>
            </el-col>
        </el-row>
        <el-dialog title="采集数据" :visible.sync="dialogTableVisible" width="20%">
            <el-table :data="gridData" height="250" border style="width: 100%">
                <el-table-column prop="date" label="时间"></el-table-column>
                <el-table-column prop="number" label="数据"></el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>
<script>
import config from '@/settings'
import echarts from 'echarts'
import { formatDate } from "@/utils/index";
require('echarts/theme/macarons')
import { apiGetDeptExt, apiGetDeptExtFindByDeptId, apiGetDeptExtFindAll, apiGetDeptExtFindBySummary } from "../../../../api/customerfiles/deptExt";
import { apiGetFindHouseholdDataBydate } from "../../../../api/electricitysales/householdData";
import { apiGetDeclareDayView, apiGetDeclareDayViewDownload } from "../../../../api/electricitysales/declareDay";
import { apiPutDeclareDayCorrect } from "../../../../api/electricitysales/declareDayCorrect";
export default {
    data(){
        return{
            userInfo: null,
            userType: null,
            rightSpanNum: 20,
            dialogTableVisible: false,
            oldCorrectNumber: '',
            sumAvgNumber: 0,
            sumForecastNumber: 0,
            sumCorrectNumber: 0,
            data : [],
            nowDate: this.getNowDate(),
            deptId: this.$route.query.deptId,
            isLookSummary: this.$route.query.deptId == 0 ? true : false,
            prompting: '',
            title:'',
            companyList: [],
            doorCount: 0,
            index: 1,
            size: 10,
            tableTotal: 0,
            isActive:0,
            // data:[
            //     {id:1,label: '山西XX111用电企业'},
            //     {id:2,label: '山西XX222用电企业'},
            //     {id:3,label: '山西XX333用电企业'}
            // ],
            dateValue: this.getNowDate(),
            activeName:'first',
            tableDataLine:[],
            seriesData01: [],
            seriesData02: [],
            elecValue:'',
            options:[
                {label:5,value:5},
                {label:10,value:10},
                {label:15,value:15},
                {label:20,value:20}
            ],
            tableData1:[],
            gridData: []
        }
    },
    created(){
        this.userInfo = this.$store.state.user.user
        this.userType = this.$store.state.user.user.userType
        this.deptId = this.userType == 5 || this.userType == 1 ? this.userInfo.deptId : this.$route.query.deptId
        setTimeout(()=>{
            this.setOptions()
        },1000)
        formatDate();
        
        this.getDeptExt()
        this.initDateTime96()
    },
    methods:{
        initDateTime96(){
            this.data = this.splitTime('2020-04-01', '2020-04-01', 96).reverse()
        },
        bindCorrectNumber(correctNumber){
            this.oldCorrectNumber = correctNumber;
        },
        editCorrectNumber(rowData, correctNumber){
            if (this.oldCorrectNumber != correctNumber) {
                let dataList = [];
                let objData = this.isLookSummary ? { declareDay: this.nowDate, number: correctNumber, time: rowData.time } : { declareDay: this.nowDate, deptId: this.deptId, number: correctNumber, time: rowData.time }
                dataList.push(objData)
                apiPutDeclareDayCorrect(dataList).then(res => {
                    this.$message({
                        type: 'success',
                        message: '执行成功!'
                    });
                    this.getDeclareDayView()
                })
                .catch(error => {
                console.log(error)
                })
            }
        },
        handleSizeChange(val) {
            this.size = val;
            this.getFindHouseholdDataBydate();
        },
        handleCurrentChange(val) {
            this.index = val;
            this.getFindHouseholdDataBydate();
        },
        search(val){
            if(val != null && val != ''){
                this.nowDate = val
                this.getFindHouseholdDataBydate()
                this.getDeclareDayView()
            }else{
                this.$message({
                    type: 'warning',
                    message: '请选择日期!'
                });
            }
        },
        reset(){
            this.dateValue = ''
        },
        getDeptExt(){
            let paramObj = {
                page: 1,
                size: 999 }
            if(this.userType != 5 && this.userType != 1){
                apiGetDeptExtFindAll(paramObj)
                .then(res => {
                    let newDataList = [];
                    if (res.length > 0) {
                    res.forEach(element => {
                        newDataList.push({ 
                        deptId: element.deptId,
                        companyName: element.name
                        });
                    });
                    }
                    this.companyList = newDataList;
                    if (this.deptId == undefined || this.deptId == null || this.deptId == '') {
                    this.deptId = newDataList[0].deptId;
                    this.isActive = newDataList[0].deptId;
                    this.getDeptExtFindByDeptId(newDataList[0].deptId);
                    this.getDeclareDayView()
                    }else{
                    this.isActive = this.deptId;
                    this.getDeptExtFindByDeptId(this.deptId);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
            }else{
                this.getDeptExtFindByDeptId(this.deptId);
            }
        },
        getDeclareDayView(){
            let paramObj = this.isLookSummary ? { declareDay: this.nowDate } : { declareDay: this.nowDate, deptId: this.deptId }
            let newtableDataLine = [];
            apiGetDeclareDayView(paramObj)
            .then(res => {
                this.data.forEach(element => {
                    let lineObj = res.list.find((n) => n.time == element)
                    if(lineObj == undefined){
                        newtableDataLine.push({time: element, avgNumber: '-', forecastNumber: '-', correctNumber: '-'});
                    }else{
                        newtableDataLine.push({time: element, avgNumber: lineObj.avgNumber, forecastNumber: lineObj.forecastNumber, correctNumber: lineObj.correctNumber});
                    }
                });
                this.tableDataLine = newtableDataLine;
                this.sumAvgNumber = res.sumAvgNumber;
                this.sumForecastNumber = res.sumForecastNumber;
                this.sumCorrectNumber = res.sumCorrectNumber;
                this.prompting = res.prompting;
                
                this.getEchartsData()
                this.setOptions();
            })
            .catch(error => {
                console.log(error);
            });
        },
        getEchartsData(){
            var _this = this
            let newSeriesData01 = [];
            let newSeriesData02 = [];
            this.data.forEach(element => {
                let lineObj = this.tableDataLine.find((n) => n.time == element)
                if(lineObj == undefined){
                    newSeriesData01.push('')
                    newSeriesData02.push('')
                }else{
                    newSeriesData01.push(lineObj.avgNumber)
                    newSeriesData02.push(lineObj.correctNumber)
                }
            });
            _this.seriesData01 = newSeriesData01
            _this.seriesData02 = newSeriesData02
        },
        setOptions(){
            let myChart = echarts.init(document.getElementById('chart_box'))
            let xdata = this.splitTime('2020-04-01', '2020-04-01', 96).reverse()
            myChart.setOption({
                title: {text: ''},
                tooltip: {
                    trigger: 'axis'
                },
                color:['rgb(14, 125, 98)','rgb(37,214,171)'],
                legend: {
                    data: ['实时数据', '修正量']
                },
                grid: {
                    left: '3%',
                    right: '2%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {},
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: xdata,
                    axisLabel: {  
                        interval:1,  
                        rotate:90  
                    }
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '实时数据',
                        type: 'line',
                        stack: '',
                        data: this.seriesData01,
                        //data: [20.4, 20.8, 21.4, 16.8, 21.4, 21.4, 17.6, 22.4, 22, 20.8, 17.8, 21.6, 20.8, 22.2, 22, 17, 22.2, 22, 21.4, 22.2, 17, 21.8, 21.4, 20.8, 20.8, 21.4, 15.4, 21.4, 20.8, 16.4, 20.6, 19.8, 20.6, 21, 21.8, 22, 21.6, 18.2, 22.6, 23.4, 22.6, 23.2, 23.4, 18, 23.8, 22.8, 19, 22.4, 17.6, 22.8, 17.6, 17.8, 22.4, 18, 22.8, 18.2, 22.8, 17.8, 22.4, 18.2, 23.4, 19.2, 23, 18.6, 23.4, 17, 22.2, 17.8, 22.8, 18.4, 22.8, 22.8, 18.8, 22.8, 22.8, 18, 22.2, 21.8, 22.6, 22.8, 22.2, 23.2, 22.4, 22.8, 18.2, 22.2, 22.6, 22, 17.4, 21, 21.4, 21.8, 17, 22, 21.4, 22.6],
                        itemStyle: {
                            normal: {
                                lineStyle: {
                                    color: 'rgb(14,125,98)'
                                }
                            }
                        }            
                    },
                    {
                        name: '修正量',
                        type: 'line',
                        stack: '',
                        data: this.seriesData02,
                        //data: [28.6, 29.117, 29.98, 23.641, 30.057, 30.01, 24.658, 31.379, 30.861, 29.256, 25.004, 30.406, 29.231, 31.075, 30.946, 23.755, 31.167, 30.871, 29.954, 31.208, 23.775, 30.581, 29.946, 29.099, 29.35, 29.991, 21.696, 29.945, 29.123, 23.008, 28.899, 27.899, 29.043, 29.461, 30.561, 30.954, 30.366, 25.598, 31.828, 32.844, 31.716, 32.504, 32.825, 25.359, 33.466, 32.072, 26.572, 31.369, 24.691, 31.894, 24.722, 24.933, 31.466, 25.336, 31.911, 25.534, 31.999, 25.062, 31.419, 25.619, 32.992, 26.9, 32.336, 26.193, 32.98, 23.902, 31.29, 24.962, 31.945, 25.732, 31.963, 32.101, 26.288, 31.895, 32.11, 25.357, 31.243, 30.546, 31.815, 31.942, 31.165, 32.506, 31.597, 31.992, 25.659, 31.223, 31.659, 30.806, 24.367, 29.438, 30.161, 30.647, 23.893, 30.89, 30.118, 32.651],
                        itemStyle: {
                            normal: {
                                lineStyle: {
                                    color: 'rgb(37,214,171)'
                                }
                            }
                        }
                    }
                ]
            })
        },
        handleNodeClick(data,node,item){
            console.log(data)
            if(data.id==1){
                this.title = '山西XX111用电企业'
            }else if(data.id==2){
                this.title = '山西XX222用电企业'
            }else if(data.id==3){
                this.title = '山西XX333用电企业'
            }
        },
        splitTime(startDate, endDate, amount) {
            var startTime = new Date(startDate + " 24:00:00"),
                endTime = new Date(endDate + " 00:00:00"),
                gap = (endTime - startTime) / amount;
            var temp = [];
            for (var i = 0; i < amount; i++) {
                startTime.setMilliseconds(startTime.getMilliseconds() + gap);
                temp[i] = new Date(startTime.getTime());
                temp[i] = temp[i].format('H:i')
            }
            return temp;
        },
        // 点击选择不同用电企业
        chooseCompany(companyId) {
            if(this.dateValue != null && this.dateValue != ''){
                this.isActive = companyId;
                
                this.companyList.forEach(element => {
                    if(element.deptId == companyId){
                        this.title = element.companyName
                    }
                });
                this.getDeptExtFindByDeptId(companyId)
                
                this.isLookSummary = companyId == 0 ? true : false;
                this.deptId = companyId;
                this.$router.push({path:'/electricitysales/realTimeData',query:{deptId:companyId}})
            }else{
                this.$message({
                    type: 'warning',
                    message: '请选择日期!'
                });
            }
            //location.reload()
        },        
        getDeptExtFindByDeptId(deptId){
            if(this.isLookSummary){
                this.title = '';
                this.doorCount = 0;
                this.getFindHouseholdDataBydate()
                this.getDeclareDayView()
            }else{
                apiGetDeptExtFindByDeptId(deptId)
                .then(res => {
                    let dataList = res;
                    this.title = res.name;
                    this.doorCount = res.equipments == null ? 0 : res.equipments.length;
                    this.getFindHouseholdDataBydate()
                    this.getDeclareDayView()
                })
                .catch(error => {
                    console.log(error);
                });
            }
        },
        getFindHouseholdDataBydate(){
            let tbItem = {}
            let newTableData1 = []
            let deptIds = []
            deptIds.push(this.deptId)
            let paramObj = this.isLookSummary ? {date: this.nowDate, page: this.index, size: this.size} : {date: this.nowDate, deptIds: deptIds.join(','), page: this.index, size: this.size}
            apiGetFindHouseholdDataBydate(paramObj)
            .then(res => {
                res.forEach(resElement => {
                    tbItem.name = resElement.dept.name;
                    tbItem.date = resElement.date;
                    tbItem.deptId = resElement.dept.deptId;
                    if (resElement.data != null) {
                        this.data.forEach(element => {
                            tbItem[element] = resElement.data[element]
                        });
                    } 
                    newTableData1.push(tbItem) 
                }); 
                this.tableData1 = newTableData1 
                this.tableTotal = res.length
                // if (res.length > 0) {
                //     aaa.name = res[0].dept.name;
                //     aaa.date = res[0].date;
                //     aaa.deptId = res[0].dept.deptId;
                //     if (res[0].data != null) {
                //         this.data.forEach(element => {
                //             aaa[element] = res[0].data[element]
                //         });
                //     } 
                //     newTableData1.push(aaa)        
                //     this.tableData1 = newTableData1 
                //     this.tableTotal = res.length
                // }
            })
            .catch(error => {
                console.log(error);
            });
        },
        getNowDate() {
            var date = new Date();
            var seperator1 = "-";
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = year + seperator1 + month + seperator1 + strDate;
            return currentdate;
        },
        lookSummary(){
            this.isLookSummary = true;
            this.deptId = 0;
            this.chooseCompany(0);
        },
        exportExcel(){
            window.location.href = config.apiUrl + "api/declareDay/viewDownload?declareDay="+ this.nowDate +"&deptId="+ this.deptId
        },
        showDetail(row){
            let newGridData = [];
            let i = 0;
            for (const key in row) {
                if(i > 2){
                newGridData.push({date:key, number:row[key]})
                }
                i++;
            }
            this.gridData = newGridData;
            this.dialogTableVisible = true;
        }
    }
}
</script>
<style>
.el-date-table td.current:not(.disabled) span{
    color: #fff !important;
}
</style>
<style scoped>

.real-time-data{
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
}
.title{
    width: 100%;
    height: 40px;
    width: 100%;
    line-height: 40px;
    text-align: center;
    font-weight: bold;
    color: #fff;
    margin: 0;
    background-color: rgb(14, 125, 98);
}
.check{
    display: inline-block;
    color: #00524a;
    font-size: 14px;
    padding: 10px 0 10px 0;
}
.theme_color{
    color: #00524a;
    border-color: #00524a;
}
.real-time-data .el-tabs__item.is-active{
    color: #00524a;
}
.real-time-data .el-tabs__active-bar{
    background-color: #00524a;
}
.real-time-data .el-tabs__item:hover{
    color: #00524a;
}
/* .real-time-data .el-tree-node__content{
    display: block;
    font-size: 14px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    color: inherit;
}
.real-time-data .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{
    background: #fff !important;
}
.real-time-data .el-tree-node__content:hover{
    background: #e6f2f0;
} 
.real-time-data .is-leaf{
    display: none;
} */
.sub-title{
    margin: 0 0 0 20px;
    color: rgb(14, 125, 98);
}
.line-2{
    font-size: 14px;
    padding: 20px;
}
.line-2 span{
    color: #999;
}
.el-tabs {
    margin: 30px 0 0 20px;
}
.real-time-data .el-table--scrollable-x .el-table__body-wrapper {
    overflow-x: hidden;
}
.overflowX .el-table__body-wrapper{
  overflow-x: auto !important;
}
.total_line_1{
  width: 98%;
  border-bottom: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
  box-shadow: 0 -5px 4px 2px rgba(119, 199, 180, 0.1);
  position: relative;
  z-index: 100;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  background-color: rgb(14, 125, 98);
}
.total_line_1 span {
  display: inline-block;
  padding: 12px 0;
  font-size: 14px;
  color: #ffffff;
  width: 23%;
  text-align: center;
}
.total_line_1 .span30{
    width: 30%;
}
.total_line_1 span b {
  display: inline-block;
  width: 100%;
  box-sizing: border-box;
  padding: 0 10px;
}
.input-value{
    width: 100%;
    color: #00524a !important;
}
.input-value input{
    width:  100% !important;
}
.real-time-data .el-button--default:hover{
    color: #00524a;
    border-color: #00524a;
    background: transparent;
}
.theme_color{
    color: #00524a;
}
.left-tree{
    height: calc(100vh - 150px);
    background: #e6f2f0;
    padding: 0 !important;
    position: relative;
}
.el-row-sumlink{
    /* position: absolute; */
    left: 0;
    bottom: 0;
    width: 100%;
    text-align: center;
}
.el-tree-border{
    background: #e6f2f0;
}
.company{
    list-style: none;
    padding-left: 0;
    margin: 0;
}
.left-company {
    height: calc(100vh - 150px);
    background: #e6f2f0;
    padding: 0 !important;
}
.all-client {
    width: 100%;
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-weight: bold;
    color: #fff;
    background-color: rgb(14, 125, 98);
}
.company-item {
    width: 100%;
    height: 40px;
    box-sizing: border-box;
    line-height: 40px;
    text-align: center;
    cursor: pointer;
    font-size: 14px;
    position: relative;
    left: 5px;
}
.active {
    border: none;
    background-color: #fff;
}
.company-name {
    margin: 0 0 0 20px;
    color: rgb(14, 125, 98);
}
.cell {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    vertical-align: middle;
    padding-left: 10px;
    padding-right: 10px;
    width: 100%;
}
.el-table th {
    padding: 12px 0;
    min-width: 0;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    text-overflow: ellipsis;
    vertical-align: middle;
    position: relative;
    text-align: left;
}
</style>